package cn.com.gensoft.app.core.shiro;

import cn.com.gensoft.app.core.utils.ShiroUtils;
import cn.com.gensoft.app.web.user.entity.SysUserEntity;
import cn.com.gensoft.app.web.user.service.SysUserService;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.Set;


/**
 * shiro realm配置 //:todo 待完善
 * @author hlj
 */
public class AppShiroRealm extends AuthorizingRealm {

	@Autowired
	private SysUserService sysUserService;

    /**
     * 授权(验证权限时调用)
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
    	String userId = ShiroUtils.getUserId();
		//用户角色
		Set<String> rolesSet = null;
		//用户权限
		Set<String> permsSet = null;
		SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
		info.setRoles(rolesSet);
		info.setStringPermissions(permsSet);
		return info;
    }

    /**
     * 认证(登录时调用)
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        UsernamePasswordToken utoken=(UsernamePasswordToken) token;
        String username = utoken.getUsername();
        SysUserEntity user = sysUserService.getByUserName(username);
        SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(user.getUsername(),
                user.getPassword(),
                ByteSource.Util.bytes(user.getUsername()),
                this.getClass().getName());
        return info;
    }
}
